package top.jlzhou.jobs.service.impl;

import top.jlzhou.jobs.entity.AccessLog;
import top.jlzhou.jobs.entity.UserInfo;
import top.jlzhou.jobs.mapper.AccessLogMapper;
import top.jlzhou.jobs.mapper.UserInfoMapper;
import top.jlzhou.jobs.service.UserInfoService;
import top.jlzhou.T;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author J.L.Zhou
 * @since 2018-10-22
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private AccessLogMapper logMapper;
	@Autowired
	private T tools;

	@Override
	@Transactional
	public long login(String userName, String userPwd, String ip) throws Exception {
		long toKen = tools.id.nextId();
		UserInfo user = null;
		
		user = baseMapper.selectById(userName);
		

		if (user == null) {
			throw new Exception("用户不存在");
		}

		if (!user.getUserPwd().equals(tools.codec.md5.encode(userPwd))) {
			throw new Exception("密码错误");
		}
		user.setToken(toKen);
		baseMapper.updateToken(user);
		AccessLog log = new AccessLog();
		log.setLogIp(ip);
		log.setLogType(1);
		log.setLogTime(LocalDateTime.now());
		log.setUserName(userName);
		logMapper.insert(log);
		return toKen;
	}

	@Override
	@Transactional
	public void check(Long token, String ip) throws Exception {
		UserInfo user = getByToken(token);
		AccessLog log = new AccessLog();
		log.setLogIp(ip);
		log.setLogType(0);
		log.setLogTime(LocalDateTime.now());
		log.setUserName(user.getUserName());
		logMapper.insert(log);
	}

	@Override
	@Transactional
	public void logout(Long token, String ip) throws Exception {
		UserInfo user = getByToken(token);
		AccessLog log = new AccessLog();
		log.setLogIp(ip);
		log.setLogType(2);
		log.setLogTime(LocalDateTime.now());
		log.setUserName(user.getUserName());
		logMapper.insert(log);
		baseMapper.clearToken(token);
	}

	@Override
	public UserInfo getByToken(Long token) {
		UserInfo user = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("TOKEN", token));
		if (user == null) {
			throw new RuntimeException("用户状态失效");
		}
		return user;

	}

	@Override
	public void save(Long token, UserInfo user) throws Exception {
		UserInfo user1 = getByToken(token);
		user.setUserName(user1.getUserName());
		user.setUserPwd(null);
		user.setUserRealName(null);
		baseMapper.updateById(user);
	}

	@Override
	public void updatePwd(Long token, String pwd1, String pwd2) throws Exception {
		UserInfo user = getByToken(token);
		if(!tools.codec.md5.encode(pwd1).equals(user.getUserPwd())) {
			throw new Exception("旧密码不正确");
		}
		user.setUserPwd(tools.codec.md5.encode(pwd2));
		baseMapper.updateById(user);
		
	}

}
